/*
 * 创建日期 2009-12-14
 *
 * 成都天和软件公司
 * 电话：028-85425861
 * 传真：028-85425861-8008
 * 邮编：610041 
 * 版权所有
 */
package  org.fantasy.common.grid.bean;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import  org.fantasy.common.grid.HttpServletRequestAware;
import  org.fantasy.common.grid.custom.BaseCellCustom;
import  org.fantasy.common.grid.custom.BaseRowCustom;
import  org.fantasy.common.grid.custom.CellCustom;
import  org.fantasy.common.grid.custom.RowCustom;
import  org.fantasy.common.grid.head.BaseTableHead;
import  org.fantasy.common.grid.head.TableHeadClass;
import  org.fantasy.common.grid.head.TableHeadDataBase;
import  org.fantasy.common.grid.head.TableHeadXml;
import  org.fantasy.common.grid.identity.BaseIdentity;
import  org.fantasy.common.grid.identity.Identity;
import  org.fantasy.common.grid.util.GridConst;
import  org.fantasy.common.util.StringUtil;
import  org.fantasy.common.util.WebUtil;

/**
 *  抽象参数配置
 * @author: 王文成
 * @version: 1.0
 * @since 2009-12-14
 */
public abstract class BaseParam implements HttpServletRequestAware, Param {

    private static final Log log = LogFactory.getLog(BaseParam.class);

    private static final String EMPTY_STRING = new String();

    protected String var = "Table";

    protected String data;

    protected String tableConfig;

    protected String action = EMPTY_STRING;

    protected boolean page;

    protected String style = "height:100%;width:100%;";

    protected String rowCustom = EMPTY_STRING;

    protected String cellCustom = EMPTY_STRING;

    protected HttpServletRequest request;

    protected String rowHeight = "20";

    protected String exportName = "REPORT";

    protected String countType;

    protected String countAction;

    protected List dataList;

    protected List<List<Column>> tableHeads;

    protected List<Column> tableFields;

    protected Set<String> hideHeads;

    protected RowCustom rowCustomIns;

    protected CellCustom cellCustomIns;

    protected Toolbar toolbar;

    protected String identity;
    
    protected BaseTableHead table;
    
    /**
     * 选择模式 单行:single 多行:multiple
     */
    protected String selectMode = "single";
    
    boolean lockHead = true;

    protected boolean prepare = false;

    public BaseParam() {
        log.debug(">>>>>>>>>>>>>>>>>>> New BaseParam instance!");
    }

    /**
     * 初始化配置
     * 
     * @throws Exception
     */
    public void prepare() throws Exception {
        if (this.prepare)
            return;
        this.identity = getIdentityValue();
        this.table = getTableHead();
        this.tableHeads = table.getTableHeads();
        this.tableFields = table.getTableFields();
        this.hideHeads = table.getHideHeads(identity);
        this.rowCustomIns = getRowCustomInstance();
        this.cellCustomIns = getCellCustomInstance();
        this.countAction = getCountActionValue();
        this.dataList = formatDataList();
        this.prepare = true;
    }

    public void setVar(String var) {
        this.var = var;
    }

    public String getVar() {
        return var;
    }
    
    public String getId() {
        return var + "ID";
    }

    public CellCustom getCellCustom() {
        return cellCustomIns;
    }

    public RowCustom getRowCustom() {
        return rowCustomIns;
    }

    public Set<String> getHideHeads() {
        return hideHeads;
    }

    public List<Column> getTableFields() {
        return tableFields;
    }

    public List<List<Column>> getTableHeads() {
        return tableHeads;
    }

    public String getRowCustomClass() {
        return rowCustom;
    }

    public void setHttpServletRequest(HttpServletRequest request) {
        this.request = request;
    }

    public void setRowCustom(String rowCustom) {
        this.rowCustom = rowCustom;
    }

    public void setData(String data) {
        this.data = data;
    }

    public void setPage(String page) {
        this.page = "true".equalsIgnoreCase(page);
    }

    public String getStyle() {
        return style;
    }

    public String getRowHeight() {
        return rowHeight;
    }

    protected void setRowHeight(String rowHeight) {
        this.rowHeight = rowHeight;
    }

    public void setStyle(String style) {
        this.style = style;
    }

    public String getAction() {
        return action;
    }

    public void setAction(String action) {
        this.action = action;
    }

    public String getCellCustomClass() {
        return cellCustom;
    }

    public void setCellCustom(String cellCustom) {
        this.cellCustom = cellCustom;
    }

    public String getTableConfig() {
        return tableConfig;
    }

    public void setTableConfig(String tableConfig) {
        this.tableConfig = tableConfig;
    }

    public boolean isPage() {
        return page;
    }

    /**
     * 取得表头配置
     * 
     * @return
     * @throws Exception
     */
    protected BaseTableHead getTableHead() throws Exception {
        if (tableConfig.startsWith("xml:")) {
            String config = tableConfig.replaceFirst("xml:", "");
            return new TableHeadXml(request, config);
        } else if (tableConfig.startsWith("class:")) {
            String config = tableConfig.replaceFirst("class:", "");
            return new TableHeadClass(request, config);
        } else if (tableConfig.startsWith("pk")) {
            String config = tableConfig.replaceFirst("pk:", "");
            return new TableHeadDataBase(request, config);
        } else {
            // 默认XML配置
            return new TableHeadXml(request, tableConfig);
        }
    }

    /**
     * 取得样式选择器
     * 
     * @return
     * @throws Exception
     */
    protected RowCustom getRowCustomInstance() throws Exception {
        if (StringUtil.isValid(rowCustom)) {
            Class cls = Class.forName(rowCustom);
            if (RowCustom.class.isAssignableFrom(cls)) {
                RowCustom custom = (RowCustom) cls.newInstance();
                custom.setHttpServletRequest(request);
                return custom;
            } else {
                throw new Exception("类型错误![" + rowCustom
                        + "] 未继承类[ org.fantasy.common.grid.custom.CellCustomSupport]或实现接口[ org.fantasy.common.grid.custom.CellCustom]");
            }
        }else{
        	BaseRowCustom custom = new BaseRowCustom();
        	custom.setHttpServletRequest(request);
        	return custom;
        }
    }

    /**
     * 取得CSS样式选择器
     * 
     * @return
     * @throws Exception
     */
    protected CellCustom getCellCustomInstance() throws Exception {
        if (StringUtil.isValid(cellCustom)) {
            Class cls = Class.forName(cellCustom);
            if (CellCustom.class.isAssignableFrom(cls)) {
                CellCustom custom = (CellCustom) cls.newInstance();
                custom.setHttpServletRequest(request);
                return custom;
            } else {
                throw new Exception("类型错误![" + cellCustom
                        + "] 未继承类[ org.fantasy.common.grid.custom.RowCustomSupport]或实现接口[ org.fantasy.common.grid.custom.RowCustom]");
            }
        }else{
        	BaseCellCustom custom = new BaseCellCustom();
        	custom.setHttpServletRequest(request);
        	return custom;
        }
    }

    public List getDataList() {
        return dataList;
    }

    /**
     * 格式化查询结果集(默认无转换)
     * 
     * @return
     * @throws Exception
     */
    @SuppressWarnings("all")
    protected List formatDataList() throws Exception {
        return (List) WebUtil.findAttribute(request, data, new ArrayList(0));
    }

    /**
     * 是否是隐藏列
     * 
     * @param col
     * @return
     */
    public boolean isHideCol(Column col) {
        Set<String> hideHeads = this.getHideHeads();
        boolean isHide = "false".equalsIgnoreCase(col.getVisible());
        boolean isInHide = hideHeads.contains(col.getId());
        return isHide || isInHide;
    }

    public Toolbar getToolbar() {
        if (toolbar == null)
            return new Toolbar();
        return toolbar;
    }

    public void setToolbar(String toolbar) {
        this.toolbar = new Toolbar(toolbar);
    }

    public String getExportName() {
        return exportName;
    }

    public void setExportName(String exportName) {
        this.exportName = exportName;
    }

    public String getIdentity() {
        return identity;
    }

    public void setIdentity(String identity) {
        this.identity = identity;
    }

    public void setCountType(String countType) {
        this.countType = countType;
    }

    public String getCountAction() {
        return countAction;
    }

    private String getCountActionValue() {
        String type = countType;
        if (!StringUtil.isValid(type))
            return GridConst.COUNT_ACTION;
        if (type.contains(".action") || type.contains(".do") || type.contains(".jsp")) {
            return type;
        } else {
            return GridConst.COUNT_ACTION + "?" + GridConst.COUNT_TYPE + "=" + type;
        }
    }

    /**
     * 取得身份值
     * 
     * @return
     * @throws Exception
     */
    private String getIdentityValue() throws Exception {
        if (!StringUtil.isValid(identity)) {
            return new BaseIdentity().getRoleId(request);
        }
        if (identity.startsWith("class:")) {
            String className = identity.replaceFirst("class:", "");
            Class cls = Class.forName(className);
            if (Identity.class.isAssignableFrom(cls)) {
                Identity ident = (Identity) cls.newInstance();
                return ident.getRoleId(request);
            } else {
                throw new Exception("类型错误![" + identity + "] 未实现接口[ org.fantasy.common.grid.identity.Identity]");
            }
        }
        return identity;
    }
    
    public void setLockHead(String lockHead) {
        this.lockHead = "true".equalsIgnoreCase(lockHead);
    }

    public boolean isLockHead() {
        return lockHead;
    }
    
    public String getSelectMode() {
        return selectMode;
    }

    public void setSelectMode(String selectMode) {
        this.selectMode = selectMode;
    }

    @Override
    public String toString() {
        JSONObject json = new JSONObject();
        json.put("var", var);
        json.put("tableConfig", tableConfig);
        json.put("page", page);
        json.put("action", action);
        json.put("style", style);
        json.put("rowCustom", rowCustom);
        json.put("cellCustom", cellCustom);
        json.put("exportName", exportName);
        json.put("identity", identity);
        return json.toString();
    }
}
